<template>
  <div class="app-container">
    <!-- 实时数据 -->
    <el-card>
      <LiveOverview :tabs="realTimeData" @refresh="getOverview()" />
    </el-card>

    <!-- 搜索栏 start -->
    <el-card class="mt-20">
      <SearchForm
        :form-option="formOption"
        :show-btn="true"
        :btn-list="btnList"
        v-model="formOption.formData"
        label-width="90px"
      />
    </el-card>
    <!-- 搜索栏 end -->

    <!-- 数据表格 start -->
    <el-card class="mt-20">
      <PageTable
        :loading="loading"
        :data="dataSource"
        :columns="columns"
        :options="options"
        @selectChange="selectChange"
      />
      <Pagination
        v-show="total > 0"
        :total="total"
        :pageNo.sync="listQuery.pageNo"
        :pageSize.sync="listQuery.pageSize"
        @pagination="getInvoiceList"
      />
    </el-card>
    <!-- 数据表格 end -->

    <!-- 开发票弹窗 -->
    <CompanyInfoOpenInvoice
      v-model="invoiceDailogShow"
      ref="openInvoice"
      @openInvoiceResult="doOpenInvoiceResult"
    />
  </div>
</template>

<script>
import CompanyInfoOpenInvoice from './components/CompanyInfoOpenInvoice.vue'
import { export2Excel } from '@/utils/export'
import { INVOICE_STATUS } from '@/enum/user'

export default {
  name: '',
  components: {
    // 开票弹窗
    CompanyInfoOpenInvoice
  },
  props: {},
  data() {
    return {
      // 开发票弹窗是否显示
      invoiceDailogShow: false,
      // 实时数据列表
      realTimeData: [
        {
          isShow: true,
          key: 'all',
          label: '全部',
          value: 0
        },
        {
          isShow: true,
          key: 'newApply',
          label: '新申请',
          value: 0
        },
        {
          isShow: true,
          key: 'already',
          label: '已开票',
          value: 0
        }
      ],

      // 表单搜索配置
      formOption: {
        items: [
          {
            type: 'daterange',
            label: '申请时间',
            value: 'time',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            clear: () => {
              // this.getList()
            }
          },
          {
            type: 'input',
            label: '注册信息',
            value: 'etpName',
            placeholder: '请输入企业名称',
            clear: () => {
              // this.getList()
            }
          }
        ],
        formData: {}
      },
      // 表单按钮列表
      btnList: [
        {
          type: 'primary',
          label: '搜索',
          onClick: () => {
            this.listQuery.pageNo = 1
            this.getInvoiceList()
          }
        },
        {
          label: '重置',
          onClick: () => {
            this.formOption.formData = {}
            this.listQuery.pageNo = 1
            this.getInvoiceList()
          }
        },
        {
          label: '导出',
          onClick: () => {
            this.exportFile()
          }
        }
      ],

      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,

      // 表格加载
      loading: true,
      // 表格配置
      options: {
        border: true,
        select: true
      },
      // 表格列配置
      columns: [
        {
          label: '原注册信息',
          width: '180px',
          render: (h, { row }) => {
            return (
              <div style={'display: flex'}>
                {row.avatar ? (
                  <img style={'width: 60px;height: 60px;'} src={row.userProfilePhoto} />
                ) : (
                  <img style={'width: 60px;height: 60px;'} src={this.avatar} />
                )}
                <div class="ml-10 pt-5 pb-5 flex flex-col justify-between align-start">
                  <p>{row.userName}</p>
                  <p>{row.userMobile}</p>
                </div>
              </div>
            )
          }
        },
        { prop: 'invoiceTitle', label: '发票抬头' },
        { prop: 'invoiceTfn', label: '发票税号' },
        {
          label: '内容/金额',
          prop: 'content',
          render: (h, { row }) => {
            return (
              <div>
                <p>{row.content}</p>
                <p>￥{row.cashAmount}</p>
              </div>
            )
          }
        },
        { prop: 'receiveTarget', label: '电子邮箱' },
        {
          label: '银行卡信息',
          prop: 'bankAddress',
          render: (h, { row }) => {
            return (
              <div>
                <p>{row.bankAddress}</p>
                <p>{row.bankAccount}</p>
              </div>
            )
          }
        },
        { prop: 'address', label: '注册地址' },
        { prop: 'orderNo', label: '开票订单' },
        {
          label: '开票状态',
          prop: 'status',
          render: (h, { row }) => {
            const typeTextObj = {
              1: '新申请',
              2: '已开票'
            }
            const btnTextObj = {
              1: '去处理',
              2: '查看记录'
            }
            const typeColorObj = {
              1: '#fc4560',
              2: '#333'
            }
            return (
              <div>
                <p style={`color:${typeColorObj[row.status]}`}>{typeTextObj[row.status]}</p>
                {row.status === 1 ? (
                  <p style="color:#409eff;cursor: pointer;" onClick={() => this.toHandle(row)}>
                    去处理
                  </p>
                ) : (
                  <el-popover placement="left" title="开票记录" width="400" trigger="click">
                    <div>
                      <div>
                        <TitleLine title="开票凭证" />
                        <el-image
                          style="width: 100px; height: 100px"
                          src={row.voucher}
                          preview-src-list={[row.voucher]}
                        ></el-image>
                      </div>
                      <div class="mt-5">
                        <TitleLine title="备注" />
                        <p>{row.remark || '暂无'}</p>
                      </div>
                      <div class="mt-5">
                        <TitleLine title="进度" />
                        <div class="flex mt-5 justify-between">
                          <p>操作员：{row.auditUser}</p>
                          <p class="ml-10">时间：{row.auditTime}</p>
                        </div>
                      </div>
                    </div>
                    <p style="color:#2a94f4;cursor: pointer;" slot="reference">
                      查看理由
                    </p>
                  </el-popover>
                )}
              </div>
            )
          }
        },
        { prop: 'createdTime', label: '申请时间' }
      ],
      // 表格源数据
      dataSource: [],
      // 选择列表
      selectList: []
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    // 获取数据概况
    this.getOverview()
    // 获取开票记录列表
    this.getInvoiceList()
  },
  methods: {
    // 获取数据概况
    async getOverview() {
      try {
        const { data } = await this.$http.user.etpInvoiceRecord.overview()
        this.realTimeData = this.realTimeData.map(el => {
          return { ...el, value: data[el.key] }
        })
      } catch (error) {
        console.log('getOverview', error)
      }
    },

    // 获取开票记录列表
    async getInvoiceList() {
      try {
        // 参数整理
        const params = {
          ...this.listQuery,
          etpId: this.$route.query.id,
          etpName: this.formOption.formData.etpName,
          startTime: this.formOption.formData?.time?.[0] ?? '',
          endTime: this.formOption.formData?.time?.[1] ?? ''
        }
        // 发送请求
        const {
          data: { records, total }
        } = await this.$http.user.etpInvoiceRecord.list({ params })
        // console.log(records, total)
        this.dataSource = records
        this.total = total
        this.loading = false
      } catch (error) {
        console.log('getInvoiceList', error)
      }
    },

    /**
     * 勾选列表行数据
     * @parma {Array} rows 选中行
     */
    selectChange(rows) {
      this.selectList = rows
    },

    /**
     * 点击去处理
     * @param {Object} row 当前行数据
     */
    toHandle({ id }) {
      this.$refs.openInvoice.id = id
      this.invoiceDailogShow = true
    },

    // 已成功处理开票
    doOpenInvoiceResult() {
      this.getInvoiceList()
    },

    // 导出表格
    exportFile() {
      if (!this.selectList.length) return this.$message.error('请选择要导出的数据')
      // 表头设置
      const headerData = this.columns.filter(item => item.prop).map(item => item.label)
      headerData.splice(0, 0, '用户昵称', '手机号码')
      // console.log(headerData)
      // 表格数据字段
      const filterData = this.columns.filter(item => item.prop).map(item => item.prop)
      filterData.splice(0, 0, 'userName', 'userMobile')
      // console.log(filterData)
      // 表格数据
      const tableData = this.selectList.map(item => {
        return {
          ...item,
          content: `${item.content}  ￥${item.cashAmount}`,
          bankAddress: `${item.bankAddress}  ${item.bankAccount}`,
          status: INVOICE_STATUS[item.status]
        }
      })
      // console.log(tableData)
      export2Excel(headerData, tableData, filterData, '开票记录', () => {
        this.$message.success('导出成功')
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
